// 📊 S4_v2策略：终极容错 精调版（线性冷却惩罚 + 近期热度奖励）
const _ = require("lodash");

function select32NumbersByS4(temp) {
  const allNumbers = Array.from({ length: 49 }, (_, i) =>
    (i + 1).toString().padStart(2, "0")
  );

  const windowSizes = [20, 40, 60];
  const scoreMap = {};
  const maxWrongMap = {};

  // 初始化连续错误记录
  let wrongStreakMap = {};
  allNumbers.forEach((n) => {
    wrongStreakMap[n] = 0;
    maxWrongMap[n] = 0;
  });

  // 遍历历史开奖，统计每个号码的最大连续不中次数
  for (let i = 0; i < temp.length; i++) {
    const actual = temp[i].number;
    allNumbers.forEach((n) => {
      if (n === actual) {
        wrongStreakMap[n] = 0;
      } else {
        wrongStreakMap[n]++;
        maxWrongMap[n] = Math.max(maxWrongMap[n], wrongStreakMap[n]);
      }
    });
  }

  // 最近10期号码（用于热度奖励）
  const recent10Numbers = new Set(temp.slice(-10).map((item) => item.number));

  // 多窗口融合评分
  windowSizes.forEach((winSize) => {
    const subTemp = temp.slice(-winSize);
    const freqMap = {};
    const lastAppearMap = {};
    const wrongStreakLocal = {};

    allNumbers.forEach((n) => (wrongStreakLocal[n] = 0));

    for (let i = subTemp.length - 1; i >= 0; i--) {
      const num = subTemp[i].number;
      allNumbers.forEach((n) => {
        if (n === num) {
          wrongStreakLocal[n] = 0;
        } else {
          wrongStreakLocal[n]++;
        }
      });

      freqMap[num] = (freqMap[num] || 0) + 1;
      lastAppearMap[num] = i;
    }

    allNumbers.forEach((n) => {
      const freq = freqMap[n] || 0;
      const lastIndex = lastAppearMap[n];
      const gap = lastIndex !== undefined ? subTemp.length - 1 - lastIndex : subTemp.length;
      const wrong = wrongStreakLocal[n] || 0;

      // ✅ 线性惩罚机制（每多错一次惩罚更多）
      const cooldownPenalty = (maxWrongMap[n] || 0) * -5;

      // ✅ 最近热号奖励（出现过就加分）
      const recentBonus = recent10Numbers.has(n) ? 10 : 0;

      const score = freq * 2 + gap * 1 - wrong * 1.5 + cooldownPenalty + recentBonus;

      scoreMap[n] = (scoreMap[n] || 0) + score;
    });
  });

  const result = Object.entries(scoreMap)
    .sort((a, b) => b[1] - a[1])
    .slice(0, 32)
    .map(([n]) => n);

  return result;
}

module.exports = select32NumbersByS4;
